<template>
	<view class="container" v-if="product != null && product.image != null">
		<view class="product-header">
			<image class="product-image" :src="product.image" mode="aspectFit" />
			<view class="product-info">
				<text class="product-name">{{ product.name }}</text>
				<text class="product-subtitle">{{ product.subtitle }}</text>

				<!-- 添加价格显示区域 -->
				<view class="product-price-area">
					<text class="original-price">原价: ¥{{ product.price || '0.00' }}</text>
					<text class="vip-price">会员价: ¥{{ product.vipPrice || '0.00' }}</text>
				</view>
			</view>
		</view>
		<view class="product-details">
			<text class="detail-title">产品详情</text>
			<view class="detail-content">
				<text class="detail-item">名称：{{ product.name }}</text>
				<text class="detail-item">品牌：{{ product.brand }}</text>
				<text class="detail-item">规格：{{ product.specification }}</text>
			</view>
		</view>
		<view class="exchange-info mt-15">
			<text class="info-title">商品图片</text>
			<view class="info-content">
				<image style="height: 349px; width: 100%;" v-for="(image, index) in productImages" :key="index"
					:src="image" mode="aspectFit" alt="产品图片" />
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<view class="cart-btn" @tap="goToCart">
				<view class="cart-icon">
					<image src="/static/image/gouwuche.png" class="icon" />
					<view class="badge" v-if="cartCount > 0">{{ cartCount }}</view>
				</view>
				<text class="cart-text">购物车</text>
			</view>
			<view class="add-btn" @tap="addToCart">
				<text>加入购物车</text>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue';
	import {
		onLoad,
		onReachBottom,
		onShow
	} from '@dcloudio/uni-app';
	import {
		getShangPinXiangQin
	} from '@/package/api/selList.js';

	// 定义响应式数据
	const product = ref(null);
	const productImages = ref([]);
	const productId = ref(null);
	const loading = ref(true);
	const error = ref('');
	const cartCount = ref(0);

	// 本地存储键名（与购物车页面一致）
	const CART_STORAGE_KEY = 'shop_cart';
	const CART_QUANTITY_KEY = 'cart_quantity';

	// 获取商品详情数据
	const fetchProductDetail = async (id) => {
		try {
			const res = await getShangPinXiangQin(id);
			console.log('接口返回数据:', res);

			if (res.data) {
				product.value = {
					...res.data,
					image: res.data.thumbnail || res.data.image || '',
					name: res.data.productName || '',
					subtitle: res.data.subtitle || '',
					brand: res.data.brand || '奥维生物',
					specification: res.data.specification || '250g',
					number: res.data.number || 'AW123456',
					feature: res.data.feature || '保湿润肤',
					exchangeText: (res.data.jiFen || 199) + '积分兑换',
					originalPrice: res.data.price || 0, // 原始价格
					vipPrice: res.data.vipPrice || 0, // 会员价格
					quantity: res.data.quantity || 0 // 商品库存数量
				};

				if (res.data.images) {
					productImages.value = res.data.images.split(',');
				} else if (res.data.thumbnail) {
					productImages.value = [res.data.thumbnail];
				} else {
					productImages.value = [
						'https://aw2025ht.kangye.xyz/api/profile/upload/srYmbYTJbylp.png'
					];
				}
			}
			loading.value = false;
		} catch (err) {
			console.error('获取商品详情失败:', err);
			error.value = '获取商品详情失败，请重试';
			loading.value = false;

			product.value = {
				image: 'https://aw2025ht.kangye.xyz/api/profile/upload/srYmbYTJbylp.png',
				name: '立美丝凡士林保湿霜干皮润肤身体乳',
				subtitle: '仅限到者自意，兑后积分不退',
				brand: '奥维生物',
				specification: '250g',
				number: 'AW123456',
				feature: '保湿润肤',
				exchangeText: '199积分兑换',
				originalPrice: 59.9, // 模拟原始价格
				vipPrice: 49.9, // 模拟会员价格
				quantity: 10 // 模拟库存数量
			};
			productImages.value = [
				'https://aw2025ht.kangye.xyz/api/profile/upload/srYmbYTJbylp.png',
				'https://aw2025ht.kangye.xyz/api/profile/upload/hukWEp8fSV1k.png'
			];
		}
	};

	// 从本地存储获取购物车数据
	const getCartFromStorage = () => {
		try {
			const cartData = uni.getStorageSync(CART_STORAGE_KEY);
			return Array.isArray(cartData) ? cartData : [];
		} catch (error) {
			console.error('获取购物车数据失败:', error);
			return [];
		}
	};

	// 保存购物车数据到本地存储
	const saveCartToStorage = (cartData) => {
		try {
			uni.setStorageSync(CART_STORAGE_KEY, cartData);
			// 计算并保存购物车总数量
			const totalQuantity = cartData.reduce((sum, item) => sum + item.quantity, 0);
			uni.setStorageSync(CART_QUANTITY_KEY, totalQuantity);
			cartCount.value = totalQuantity;
			console.log('购物车数据已保存，总数量:', totalQuantity);
		} catch (error) {
			console.error('保存购物车数据失败:', error);
		}
	};

	// 页面显示时触发
	onShow(async (options) => {
		try {
			// 从本地存储获取购物车数量
			const totalQuantity = uni.getStorageSync(CART_QUANTITY_KEY) || 0;
			cartCount.value = totalQuantity;

			const shangPinId = uni.getStorageSync('shangPinId');
			console.log('获取到的商品ID:', shangPinId);

			if (shangPinId) {
				await fetchProductDetail(shangPinId);
			} else {
				product.value = {
					image: 'https://aw2025ht.kangye.xyz/api/profile/upload/srYmbYTJbylp.png',
					name: '立美丝凡士林保湿霜干皮润肤身体乳',
					subtitle: '仅限到者自意，兑后积分不退',
					brand: '奥维生物',
					specification: '250g',
					number: 'AW123456',
					feature: '保湿润肤',
					exchangeText: '199积分兑换',
					originalPrice: 59.9, // 模拟原始价格
					vipPrice: 49.9, // 模拟会员价格
					quantity: 10 // 模拟库存数量
				};
				productImages.value = [
					'https://aw2025ht.kangye.xyz/api/profile/upload/srYmbYTJbylp.png',
					'https://aw2025ht.kangye.xyz/api/profile/upload/hukWEp8fSV1k.png'
				];
				loading.value = false;
			}
		} catch (err) {
			console.error('页面显示时获取数据失败:', err);
		}
	});

	// 跳转提交订单
	const toSubmitOrder = () => {
		console.log('跳转提交订单');
		uni.navigateTo({
			url: '/package/pages/submitOrder/submitOrder'
		});
	};

	// 加入购物车（使用与购物车页面一致的数据格式）
	const addToCart = () => {
		if (!product.value) return;

		const cartData = getCartFromStorage();
		const productId = product.value.id || Date.now();

		// 查找商品在购物车中的索引
		const existingIndex = cartData.findIndex(item => item.id === productId);

		// 计算要添加的数量（首次添加为1，已有则增加1）
		const quantityToAdd = existingIndex > -1 ? cartData[existingIndex].quantity + 1 : 1;

		// 检查库存
		if (quantityToAdd > product.value.quantity) {
			uni.showToast({
				title: '库存不足',
				icon: 'none'
			});
			return;
		}

		if (existingIndex > -1) {
			// 更新购物车中商品数量
			cartData[existingIndex].quantity = quantityToAdd;
		} else {
			// 添加新商品到购物车
			cartData.push({
				id: productId,
				name: product.value.name,
				image: product.value.image,
				price: product.value.vipPrice || product.value.price || 0, // 使用会员价或原价
				vipPrice: product.value.vipPrice || 0,
				quantity: quantityToAdd,
				originalPrice: product.value.originalPrice || 0
			});
		}

		// 保存购物车数据
		saveCartToStorage(cartData);

		uni.showToast({
			title: '已加入购物车',
			icon: 'success',
			duration: 2000
		});
	};

	// 前往购物车
	const goToCart = () => {
		uni.navigateTo({
			url: '/pages/cart/cart'
		});
	};
</script>

<style>
	.container {
		padding: 16px;
		background-color: #f0f0f0;
		padding-bottom: 120rpx;
		/* 为底部导航栏留出更多空间 */
	}

	.product-header {
		display: flex;
		align-items: center;
		background-color: #ffffff;
		padding: 15px;
		border-radius: 8px;
		margin-bottom: 10px;
	}

	.product-image {
		width: 100px;
		height: 100px;
		margin-right: 15px;
	}

	.product-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.product-name {
		font-size: 16px;
		font-weight: bold;
		letter-spacing: 1px;
		margin-bottom: 10px;
	}

	.product-subtitle {
		font-size: 12px;
		color: #888;
		margin-bottom: 10px;
	}

	/* 价格显示区域样式 */
	.product-price-area {
		display: flex;
		flex-direction: column;
	}

	.original-price {
		font-size: 14px;
		color: #999;
		/* 移除删除线 */
		text-decoration: none;
		margin-bottom: 2px;
	}

	.vip-price {
		font-size: 16px;
		color: #f26b00;
		font-weight: bold;
	}

	.exchange-button {
		margin-bottom: 15px;
	}

	.exchange-btn {
		background-color: #f26b00;
		color: white;
		padding: 2px 16px;
		text-align: center;
		border-radius: 5px;
	}

	.product-details {
		background-color: white;
		padding: 15px;
		border-radius: 8px;
		margin-bottom: 15px;
	}

	.detail-title {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 20px;
	}

	.detail-content {
		margin-bottom: 15px;
	}

	.detail-item {
		font-size: 14px;
		color: #888;
		display: block;
		margin-bottom: 10px;
	}

	.exchange-info {
		background-color: white;
		padding: 15px;
		border-radius: 8px;
	}

	.info-title {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 10px;
	}

	.info-content {
		margin-bottom: 15px;
	}

	.info-item {
		font-size: 14px;
		color: black;
		display: block;
		margin-bottom: 10px;
		letter-spacing: 1px;
	}

	.gold-text {
		color: gold;
	}

	.mt-15 {
		margin-top: 15px;
	}

	/* 底部操作栏样式 */
	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 120rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 30rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.cart-btn {
		width: 120rpx;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.cart-icon {
		position: relative;
		width: 60rpx;
		height: 60rpx;
	}

	.icon {
		width: 100%;
		height: 100%;
	}

	.badge {
		position: absolute;
		top: -8rpx;
		right: -8rpx;
		width: 30rpx;
		height: 30rpx;
		background-color: #f53f3f;
		color: #fff;
		border-radius: 50%;
		text-align: center;
		line-height: 30rpx;
		font-size: 20rpx;
	}

	.cart-text {
		margin-top: 4rpx;
		font-size: 22rpx;
		color: #333;
	}

	.add-btn {
		flex: 1;
		margin-left: 20rpx;
		height: 80rpx;
		background-color: #f26b00;
		color: #fff;
		border-radius: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
	}
</style>